
package com.kugou.game.sdk.api.online;

import com.kugou.framework.base.LogUtil;
import com.kugou.framework.utils.NetWorkUtil;
import com.kugou.game.sdk.api.common.BasePlatform;
import com.kugou.game.sdk.api.common.BaseSDKConfig;
import com.kugou.game.sdk.api.common.IEventCode;
import com.kugou.game.sdk.api.common.IEventDataField;
import com.kugou.game.sdk.api.common.OnExitListener;
import com.kugou.game.sdk.api.common.OnPlatformEventListener;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.PlatformEventDispatcher;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.hotfix.MultiDex;
import com.kugou.game.sdk.interfaces.OnLoginListener;
import com.kugou.game.sdk.interfaces.OnRegisterListener;
import com.kugou.game.sdk.interfaces.OnSSOListener;
import com.kugou.game.sdk.interfaces.OnTempUserCreateListener;
import com.kugou.game.sdk.ui.activity.LoginActivity;
import com.kugou.game.sdk.ui.dialog.ExitGiftBagDialog;
import com.kugou.game.sdk.ui.dialog.LoginDialog;
import com.kugou.game.sdk.ui.dialog.LoginDialog.OnClickAccountChangeListener;
import com.kugou.game.sdk.ui.widget.FloatView;
import com.kugou.game.sdk.utils.AppUncaughtExceptionHandler;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.DESUtil;
import com.kugou.game.sdk.utils.MD5Util;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.SSOHelper;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 描述:网游SDK调用类
 * 
 * @author chenys
 * @since 2014-12-15 下午8:20:05
 */
public class KGPlatform extends BasePlatform {

    private static final int SDK_VERSION_CODE = 560;

    private static final String SDK_VERSION_NAME = "5.6.0";

    public static void init(Context context, BaseSDKConfig sdkConfig,
            OnPlatformEventListener eventListener) {
        loadDex(context);

        SDKControler.init(context, sdkConfig, SDK_VERSION_CODE, SDK_VERSION_NAME, eventListener);
        // 启动推送服务
        AppUtil.startPushService(context, sdkConfig, SDK_VERSION_CODE, SDK_VERSION_NAME);

    }

    private static void loadDex(Context context) {
        try {
            MultiDex.install(context, MultiDex.MultiDexType.HACK);
            MultiDex.loadPatch(context, SDK_VERSION_CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示欢迎信息
     * 
     * @param activity
     */
    public static void showWelcomeDialog(Activity activity) {
        checkInit();
        View contentView = activity.getLayoutInflater().inflate(Rx.layout.kg_welcome_popwindow,
                null);
        TextView tv = (TextView) contentView.findViewById(Rx.id.kg_welcom_tips_text);

        int[] wh = AppUtil.getScreenSize(activity);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tv.getLayoutParams();
        lp.width = (int) (wh[0] * 0.8);

        String tips;
        User user = UserManager.getInstance().getCurrentUserInternal();
        if (user != null && user.isRegistered()) {
            tips = "欢迎" + user.getAccountName() + "来到酷狗游戏！";
        } else {
            tips = "酷狗游戏-欢迎您到来！";
        }
        tv.setText(tips);

        Toast toast = new Toast(activity);
        // 设置Toast的位置
        toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 50);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(contentView);
        toast.show();
    }

    /** 是否已经进入过礼包领取页面 */
    private static boolean mEnterGiftBagPage = false;

    private static boolean mClickExitButton = false;

    /**
     * 退出游戏时检查是否有礼包，如果有则弹框
     * 
     * @param activity
     * @param roleName 角色名
     * @param roleLevel 角色等级
     * @param listener
     */
    public static void exitGame(final Activity activity, final String roleName,
            final int roleLevel, final OnExitListener listener) {
        checkInit();

        PlatformEventDispatcher.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final User user = UserManager.getInstance().getCurrentUserInternal();
                if (user != null && !mEnterGiftBagPage && user.isCanGetGift() && user.isHasGift()) {
                    final ExitGiftBagDialog dialog = new ExitGiftBagDialog(activity);
                    dialog.setOkBtnText("领取礼包");
                    dialog.setCancelBtnText("退出游戏");
                    dialog.setMessage("不玩了？还有礼包哦，领取礼包再继续吧~");
                    dialog.setOKClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            enterGiftBagCenter(activity);
                            mEnterGiftBagPage = true;
                            dialog.dismiss();
                        }

                    });

                    dialog.setOnDismissListener(new OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            if (!mClickExitButton && !mEnterGiftBagPage) {
                                if (listener != null) {
                                    listener.onDialogDismiss();
                                }
                            }

                        }
                    });

                    dialog.setCancelClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // 发送退出游戏统计
                            sendExitGameStatics(roleName, roleLevel);

                            if (listener != null) {
                                mClickExitButton = true;
                                dialog.dismiss();
                                try {
                                    listener.exitGame(OnExitListener.STATE_GIFTBAG_YES);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        }

                    });
                    dialog.show();
                    mClickExitButton = false;
                } else {
                    // 发送退出游戏统计
                    sendExitGameStatics(roleName, roleLevel);

                    if (listener != null) {
                        try {
                            listener.exitGame(OnExitListener.STATE_GIFTBAG_NO);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        });

    }

    // 是否正在进入游戏
    private static boolean mEnteringGame;

    // 是否正在切换账号
    private static boolean mIsChangingAccount = false;

    /**
     * 进入游戏
     * 
     * @param activity
     * @param listener
     */
    public static void enterGame(final Activity activity) {
        checkInit();
        checkDebugMode();

        if (!NetWorkUtil.isNetworkAvailable(activity)) {
            Toast.makeText(activity, "请检查您的网络连接", Toast.LENGTH_SHORT).show();
            return;
        }
        // 防止重复登陆
        if (mEnteringGame) {
            return;
        }
        mEnteringGame = true;
        mIsChangingAccount = false;

        // 异常崩溃统计和日志上传处理
        Thread.setDefaultUncaughtExceptionHandler(new AppUncaughtExceptionHandler(activity));

        // 显示登录进度对话框
        showLoginDialog(activity);

        // 2秒后进行游戏登录操作
        PlatformEventDispatcher.runOnUiThreadDelayed(new Runnable() {
            @Override
            public void run() {
                if (mIsChangingAccount) {
                    return;
                }
                loginGame(activity);
            }
        }, 2000);

    }

    private static void loginGame(Activity activity) {
        User user = UserManager.getInstance().getLastestUserDataOnSP();
        if (user == null) {
            // 取不到SP缓存帐号,启动单点登陆
            startSSOWithoutAccount(activity);
        } else {
            if (!user.isRegistered()) {
                // 有临时帐号，启动单点登陆
                startSSOWithTempAccount(user);
            } else {
                // 正式账号自动登录
                autoLogin(user, activity);
            }
        }
    }

    private static LoginDialog mLoginingDialog;

    /**
     * 显示登录加载框
     */
    private static void showLoginDialog(final Activity activity) {
        if (activity.isFinishing()) {
            return;
        }
        if (mLoginingDialog != null) {
            mLoginingDialog.cancel();
            mLoginingDialog = null;
        }

        mLoginingDialog = LoginDialog.initDialog(activity);
        User user = UserManager.getInstance().getLastestUserDataOnSP();
        if (user != null && user.isRegistered()) {
            mLoginingDialog.setLoginUserName(user.getAccountName());
        }
        mLoginingDialog.setOnClickAccountChangeListener(new OnClickAccountChangeListener() {
            @Override
            public void clickChangeAccount() {
                mIsChangingAccount = true;
                mEnteringGame = false;
                mLoginingDialog.dismiss();

                // 跳转到登录界面
                Intent intent = new Intent(activity, LoginActivity.class);
                intent.putExtra(BaseCommonTitleFragmentActivity.FROM_ACTION_KEY,
                        BaseCommonTitleFragmentActivity.FROM_BEFORE_ENTER_GAME_LOGIN);
                activity.startActivity(intent);
            }
        });
        mLoginingDialog.show();
    }

    private static void autoLogin(User user, final Activity activity) {
        // 自动登录
        final String userName = user.getAccountName();
        final String password = user.getPassword();
        final long appId = SDKControler.getAppId();
        final long tAppId = user.getKugouTokenAppId();
        final String kugouToken = user.getKugouToken();
        final OnLoginListener listener = new OnLoginListener() {
            @Override
            public void onSuccess(User user) {
                enterGameSuccess(user);
            }

            @Override
            public void onFailed(String errorMsg) {
                // 有正式账号，自动登录失败后，要跳到用户登录界面，让用户自行输入
                enterGameFailed(errorMsg);
                Intent intent = new Intent(activity, LoginActivity.class);
                intent.putExtra(BaseCommonTitleFragmentActivity.FROM_ACTION_KEY,
                        BaseCommonTitleFragmentActivity.FROM_BEFORE_ENTER_GAME_LOGIN);
                activity.startActivity(intent);
            }

        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(password)) {
                    // 密码为空，使用token登陆
                    UserManager.getInstance().login(userName, kugouToken, appId, 1, tAppId,
                            listener);
                } else {
                    // 使用密码登陆
                    UserManager.getInstance().login(userName, password, appId, 0, 0, listener);
                }

                mEnteringGame = false;
            }

        }).start();
    }

    /**
     * 取不到缓存帐号,启动单点登陆
     */
    private static void startSSOWithoutAccount(final Activity activity) {
        long appId = SDKControler.getAppId();
        String appKey = SDKControler.getAppKey();
        String packageName = SDKControler.getContext().getPackageName();
        String key = MD5Util.getMd5(appKey).substring(0, 8);
        String enPackageName = DESUtil.encrypt(packageName, key);
        HashMap<String, Object> hash = new HashMap<String, Object>();
        hash.put("appId", "" + appId);
        hash.put("appKey", appKey);
        hash.put("packageName", enPackageName);
        String jsonStr = AppUtil.convertHashMapToJson(hash);

        SSOHelper.startSingleSignOn(SDKControler.getContext(), jsonStr, new OnSSOListener() {

            @Override
            public void onComplete(String jsonStr) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    String userName = jsonObj.getString("userName");
                    String token = jsonObj.getString("token");
                    long userId = jsonObj.getLong("userId");
                    LogUtil.d("dax", "kugou_userName:" + userName);
                    LogUtil.d("dax", "kugou_token:" + token);
                    LogUtil.d("dax", "kugou_userId:" + userId);
                    loginByToken(activity, userName, token);
                } catch (JSONException e) {
                    e.printStackTrace();
                    loginWithUserDataOnSDcard(activity);
                }
            }

            @Override
            public void onError(int errorCode) {
                // 单点登陆失败,使用SD卡的账号登陆
                loginWithUserDataOnSDcard(activity);
            }
        });
    }

    /**
     * 使用SD卡的用户信息登录
     */
    private static void loginWithUserDataOnSDcard(Activity activity) {
        User user = UserManager.getInstance().getLastestUserDataOnSDcard();
        if (user == null) {
            // SD卡没有账号,请求分配临时账号
            createTempUser();
        } else {
            if (!user.isRegistered()) {
                // 有临时帐号，使用临时账号登陆
                loginByTempUser(user);
            } else {
                // 正式账号自动登录
                autoLogin(user, activity);
            }
        }
    }

    /**
     * 有临时帐号,启动单点登陆
     */
    private static void startSSOWithTempAccount(final User user) {
        long appId = SDKControler.getAppId();
        String appKey = SDKControler.getAppKey();
        String packageName = SDKControler.getContext().getPackageName();
        String key = MD5Util.getMd5(appKey).substring(0, 8);
        String enPackageName = DESUtil.encrypt(packageName, key);
        HashMap<String, Object> hash = new HashMap<String, Object>();
        hash.put("appId", "" + appId);
        hash.put("appKey", appKey);
        hash.put("packageName", enPackageName);
        String jsonStr = AppUtil.convertHashMapToJson(hash);

        SSOHelper.startSingleSignOn(SDKControler.getContext(), jsonStr, new OnSSOListener() {

            @Override
            public void onComplete(String jsonStr) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    String userName = jsonObj.getString("userName");
                    String token = jsonObj.getString("token");
                    long userId = jsonObj.getLong("userId");
                    // 单点登陆成功,绑定酷狗账号
                    bindKugouAccount(userName, token, user);
                } catch (JSONException e) {
                    e.printStackTrace();
                    loginByTempUser(user);
                }
            }

            @Override
            public void onError(int errorCode) {
                // 单点登陆失败,使用临时账号登陆
                loginByTempUser(user);
            }
        });
    }

    /**
     * 单点登陆，需要联网分配一个临时帐号
     */
    private static void createTempUser() {
        final OnTempUserCreateListener createUserListener = new OnTempUserCreateListener() {
            @Override
            public void onSuccess(User tempUser) {
                enterGameSuccess(tempUser);
            }

            @Override
            public void onFailed(String errorMsg) {
                enterGameFailed(errorMsg);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserManager.getInstance().createTempUser(createUserListener);
                mEnteringGame = false;
            }
        }).start();
    }

    /**
     * 临时帐号登陆
     */
    private static void loginByTempUser(User user) {
        // 临时帐号，直接登录
        if (user == null) {
            return;
        }
        final long appId = SDKControler.getAppId();
        final String nickName = user.getAccountName();
        final String password = user.getPassword();
        final OnLoginListener loginListener = new OnLoginListener() {
            @Override
            public void onSuccess(User user) {
                enterGameSuccess(user);
            }

            @Override
            public void onFailed(String errorMsg) {
                enterGameFailed(errorMsg);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserManager.getInstance().login(nickName, password, appId, 0, 0, loginListener);
                mEnteringGame = false;
            }
        }).start();

    }

    /**
     * 使用sso返回的token进行登陆
     * 
     * @param userName 用户名
     * @param token 用户令牌
     */
    private static void loginByToken(final Activity activity, final String userName,
            final String token) {
        final long appId = SDKControler.getAppId();
        final OnLoginListener loginListener = new OnLoginListener() {
            @Override
            public void onSuccess(User user) {
                enterGameSuccess(user);
            }

            @Override
            public void onFailed(String errorMsg) {
                loginWithUserDataOnSDcard(activity);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 这里两个appId一致
                UserManager.getInstance().login(userName, token, appId, 1, appId, loginListener);
                mEnteringGame = false;
            }
        }).start();
    }

    /**
     * 将临时账号绑定酷狗账号
     */
    private static void bindKugouAccount(final String userName, final String token, final User user) {
        final long appId = SDKControler.getAppId();
        final OnRegisterListener onRegisterListener = new OnRegisterListener() {

            @Override
            public void onSuccess(User newUser) {
                enterGameSuccess(newUser);
                mEnteringGame = false;
            }

            @Override
            public void onFailed(String errorMsg, String errorCode) {
                // 临时账号绑定正式账号失败，直接使用临时账号登陆
                loginByTempUser(user);

            }

            @Override
            public void onRecommendRegisterName(ArrayList<String> names) {
                // 对于绑定账号来说，用户名已经存在和绑定失败是一样的，所以处理逻辑一样
                loginByTempUser(user);
            }

        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserManager.getInstance().bindTempAccout(userName, user.getAccountName(), appId,
                        token, onRegisterListener);
            }
        }).start();
    }

    private static void enterGameSuccess(User user) {
        if (mIsChangingAccount) {
            return;
        }

        if (mLoginingDialog != null && mLoginingDialog.isShowing()) {
            mLoginingDialog.dismiss();
        }

        // 发送进入游戏回调
        int eventCode = IEventCode.ENTER_GAME_SUCCESS;
        Bundle data = new Bundle();
        data.putSerializable(IEventDataField.EXTRA_USER, user);
        PlatformEventDispatcher.sendEvent(eventCode, data);
        AppUtil.handleActionsAfterLoginSuccess(eventCode);
    }

    private static void enterGameFailed(final String errorMsg) {
        if (mIsChangingAccount) {
            return;
        }

        if (mLoginingDialog != null && mLoginingDialog.isShowing()) {
            mLoginingDialog.dismiss();
        }
        int eventCode = IEventCode.ENTER_GAME_FAILED;
        Bundle data = new Bundle();
        data.putString(IEventDataField.EXTRA_ERROR_MESSAGE, errorMsg);
        PlatformEventDispatcher.sendEvent(eventCode, data);

    }

    /**
     * 进入用户中心
     */
    public static void enterUserCenter(Activity activity) {
        checkInit();
        SDKControler.enterUserCenter(activity);
    }

    /**
     * 进入礼包中心
     */
    public static void enterGiftBagCenter(Activity activity) {
        checkInit();
        SDKControler.enterGiftBagCenter(activity);
    }

    /**
     * 进入游戏论坛
     */
    public static void enterGameForum(Activity activity) {
        checkInit();
        SDKControler.enterGameForum(activity);
    }

    public static void showToolBar(Activity activity, int position) {
        checkInit();
        FloatView.getInstance(activity, position).show();
    }

    public static void showToolBar(Activity activity) {
        checkInit();
        FloatView.getInstance(activity).show();
    }

    public static void hideToolBar(Activity activity) {
        checkInit();
        FloatView.getInstance(activity).hide();
    }

    public static void recycleToolBar(Activity activity) {
        checkInit();
        FloatView.getInstance(activity).release();
    }

}
